package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.JsonObject;
import com.hmdp.dto.Result;
import com.hmdp.entity.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
  @Resource
   private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        //缓存穿透
       // queryWithPassThrough(id);
        //互斥锁解决缓存击穿
       // Shop shop = queryWithMutex(id);
        //逻辑过期
        Shop shop = queryWithLogicalExpire(id);
        //返回结果
       return  Result.ok(shop);
    }

    //缓存击穿
    public Shop queryWithMutex(Long id){
        String key = "cache:shop:" + id;
        //1.先从redis缓存中查询
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否有缓存
        if (StrUtil.isNotBlank(shopJson)){
            //3.有缓存，直接返回
            return  JSONUtil.toBean(shopJson, Shop.class);
        }
        if(shopJson!=null){
            return null;
        }
        //实现缓存重建
        //3.无缓存，获取互斥锁
        String lockKey = "lock:shop:" + id;
        boolean trylock = trylock(lockKey);
        Shop shopById=null;
        try {
            //4.判断是否获取成功
            if (!trylock){
                //获取互斥锁失败，则休眠并重试
                Thread.sleep(50);
                queryWithMutex(id);
            }

            //获取成功，则查询数据库
            shopById = getById(id);
            Thread.sleep(50);
            //5.不存在，放回错误结果
            if (shopById == null){
                stringRedisTemplate.opsForValue().set(key,"", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //6.存在，放入缓存
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shopById), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            //7.释放互斥锁
        }catch (InterruptedException e){
            throw new RuntimeException(e);
        }finally {
            unlock(lockKey);
        }

        return shopById;
    }
    //获取互斥锁
    private  boolean trylock(String key){
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10L, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(true);
    }
    //释放互斥锁
    private  void   unlock(String key){
        stringRedisTemplate.delete(key);
    }
    //缓存穿透
    private Shop queryWithPassThrough(Long id){
        String key = "cache:shop:" + id;
        //1.先从redis缓存中查询
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否有缓存
        if (StrUtil.isNotBlank(shopJson)){
            //3.有缓存，直接返回
            return  JSONUtil.toBean(shopJson, Shop.class);
        }
        if(shopJson!=null){
            return null;
        }
        //4.无缓存，查询数据库
        Shop shopById = getById(id);
        //5.不存在，放回错误结果
        if (shopById == null){
            stringRedisTemplate.opsForValue().set(key,"", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //6.存在，放入缓存
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shopById), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shopById;
    }
    //预热缓存
    public  void  saveRedis(Long id,Long expireTime){
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(LocalDateTime.now().plusSeconds(expireTime));
        redisData.setDate(shop);
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY,JSONUtil.toJsonStr(shop));
    }
    //创建线程池
     private static  final ExecutorService CACHE_REBUILD_POOL = Executors.newFixedThreadPool(10);


    //    逻辑过期
    private Shop queryWithLogicalExpire(Long id){
        String key = "cache:shop:" + id;
        //1.先从redis缓存中查询
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否有缓存
        if (StrUtil.isBlank(shopJson)){
            //如果未命中，直接返回
            return  null;
        }
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getDate(), Shop.class);
        LocalDateTime data = redisData.getData();
        //3.判断是否过期
        if (data.isAfter(LocalDateTime.now())){
            //4.未过期，直接返回

            return  shop;
        }
        log.info("=============================================");
        //过期，需要缓存重建
        //获取互斥锁
        String lockKey=RedisConstants.LOCK_SHOP_KEY+id;
        boolean trylock = trylock(lockKey);
        if (trylock){
            try {
                //获取成功,开启对立线程，实现缓存重建
                CACHE_REBUILD_POOL.submit(()->{
                    this.saveRedis(id,20L);
                });
            }catch (Exception e){
                throw new RuntimeException(e);
            }finally {
                //释放互斥锁
                unlock(lockKey);
            }
        }
      //返回商品过期时间
        return  shop;
    }
    @Override
    @Transactional
    public Result updateshop(Shop shop) throws InterruptedException {
        Long id = shop.getId();
        if (id == null){
            return Result.fail("店铺ID不能为空");
        }
        //1.更新数据库
       updateById(shop);
        Thread.sleep(200);
        //2.更新缓存
        stringRedisTemplate.delete("cache:shop:"+id);
        return Result.ok();
    }
}
